#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
持久化机制场景测试模块
Persistence Mechanism Scenario Testing Module

该模块实现：
1. SSH密钥持久化场景
2. 定时任务持久化场景
3. 系统服务持久化场景
4. 启动脚本持久化场景
5. 用户账户持久化场景
6. 内核模块持久化场景
"""

import os
import sys
import time
import random
import subprocess
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

@dataclass
class PersistenceTest:
    """持久化测试结果"""
    test_id: str
    test_name: str
    method: str
    persistence_level: str  # low, medium, high, critical
    stealth_rating: float
    survival_rate: float  # 重启后存活率
    detection_difficulty: float
    cleanup_difficulty: float
    execution_time: float
    artifacts: List[str]
    persistence_locations: List[str]
    recommendations: List[str]

class PersistenceScenarios:
    """持久化场景测试器"""
    
    def __init__(self, target_host: str = "101.37.80.173"):
        self.target_host = target_host
        self.test_results: List[PersistenceTest] = []
        
    def test_ssh_key_persistence(self) -> PersistenceTest:
        """测试SSH密钥持久化"""
        print("🔑 测试SSH密钥持久化场景...")
        
        # 模拟SSH密钥部署
        ssh_locations = [
            {"path": "/root/.ssh/authorized_keys", "user": "root", "stealth": 0.6, "survival": 0.95},
            {"path": "/home/user/.ssh/authorized_keys", "user": "user", "stealth": 0.8, "survival": 0.90},
            {"path": "/etc/ssh/sshd_config", "user": "system", "stealth": 0.4, "survival": 0.98},
            {"path": "/home/admin/.ssh/authorized_keys", "user": "admin", "stealth": 0.7, "survival": 0.85}
        ]
        
        # 模拟密钥生成和部署
        deployed_keys = []
        for location in ssh_locations[:3]:  # 部署前3个位置
            key_info = {
                "location": location["path"],
                "user": location["user"],
                "key_type": "ed25519",
                "stealth": location["stealth"],
                "survival": location["survival"],
                "deployed": True
            }
            deployed_keys.append(key_info)
            print(f"  ✅ 部署SSH密钥: {location['path']} (用户: {location['user']})")
        
        # 计算平均指标
        avg_stealth = sum(key["stealth"] for key in deployed_keys) / len(deployed_keys)
        avg_survival = sum(key["survival"] for key in deployed_keys) / len(deployed_keys)
        
        test_result = PersistenceTest(
            test_id="persist_ssh_001",
            test_name="SSH密钥持久化测试",
            method="ssh_key_injection",
            persistence_level="high",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.7,
            cleanup_difficulty=0.3,
            execution_time=random.uniform(2.0, 5.0),
            artifacts=[
                f"生成 {len(deployed_keys)} 个SSH密钥对",
                f"部署到 {len(deployed_keys)} 个位置",
                "创建备用访问路径"
            ],
            persistence_locations=[key["location"] for key in deployed_keys],
            recommendations=[
                "优先使用普通用户账户降低检测风险",
                "使用ed25519密钥类型提高安全性",
                "定期轮换密钥避免长期暴露"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def test_cron_persistence(self) -> PersistenceTest:
        """测试定时任务持久化"""
        print("⏰ 测试定时任务持久化场景...")
        
        # 模拟cron持久化方法
        cron_methods = [
            {"type": "user_crontab", "location": "/var/spool/cron/crontabs/user", "stealth": 0.8, "survival": 0.90},
            {"type": "system_crontab", "location": "/etc/crontab", "stealth": 0.5, "survival": 0.95},
            {"type": "cron_d", "location": "/etc/cron.d/system-update", "stealth": 0.7, "survival": 0.92},
            {"type": "cron_hourly", "location": "/etc/cron.hourly/cleanup", "stealth": 0.6, "survival": 0.88}
        ]
        
        # 模拟部署过程
        deployed_crons = []
        for method in cron_methods:
            cron_info = {
                "type": method["type"],
                "location": method["location"],
                "schedule": self._generate_cron_schedule(),
                "command": "/tmp/.hidden/backdoor.sh",
                "stealth": method["stealth"],
                "survival": method["survival"],
                "deployed": True
            }
            deployed_crons.append(cron_info)
            print(f"  ✅ 部署定时任务: {method['type']} ({cron_info['schedule']})")
        
        # 计算平均指标
        avg_stealth = sum(cron["stealth"] for cron in deployed_crons) / len(deployed_crons)
        avg_survival = sum(cron["survival"] for cron in deployed_crons) / len(deployed_crons)
        
        test_result = PersistenceTest(
            test_id="persist_cron_001",
            test_name="定时任务持久化测试",
            method="cron_job_injection",
            persistence_level="medium",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.6,
            cleanup_difficulty=0.4,
            execution_time=random.uniform(1.0, 3.0),
            artifacts=[
                f"创建 {len(deployed_crons)} 个定时任务",
                "生成后门脚本",
                "设置执行权限"
            ],
            persistence_locations=[cron["location"] for cron in deployed_crons],
            recommendations=[
                "使用用户级crontab降低权限需求",
                "设置随机执行时间避免规律性",
                "伪装成系统维护任务"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def test_service_persistence(self) -> PersistenceTest:
        """测试系统服务持久化"""
        print("🔧 测试系统服务持久化场景...")
        
        # 模拟服务持久化方法
        service_methods = [
            {"type": "systemd_service", "location": "/etc/systemd/system/system-monitor.service", "stealth": 0.7, "survival": 0.98},
            {"type": "init_d_service", "location": "/etc/init.d/network-check", "stealth": 0.6, "survival": 0.95},
            {"type": "rc_local", "location": "/etc/rc.local", "stealth": 0.5, "survival": 0.90},
            {"type": "systemd_timer", "location": "/etc/systemd/system/cleanup.timer", "stealth": 0.8, "survival": 0.96}
        ]
        
        # 模拟服务创建
        deployed_services = []
        for method in service_methods[:3]:  # 部署前3个
            service_info = {
                "type": method["type"],
                "location": method["location"],
                "name": self._generate_service_name(),
                "description": self._generate_service_description(),
                "stealth": method["stealth"],
                "survival": method["survival"],
                "auto_start": True,
                "deployed": True
            }
            deployed_services.append(service_info)
            print(f"  ✅ 创建系统服务: {service_info['name']} ({method['type']})")
        
        # 计算平均指标
        avg_stealth = sum(service["stealth"] for service in deployed_services) / len(deployed_services)
        avg_survival = sum(service["survival"] for service in deployed_services) / len(deployed_services)
        
        test_result = PersistenceTest(
            test_id="persist_service_001",
            test_name="系统服务持久化测试",
            method="service_installation",
            persistence_level="critical",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.8,
            cleanup_difficulty=0.6,
            execution_time=random.uniform(3.0, 8.0),
            artifacts=[
                f"创建 {len(deployed_services)} 个系统服务",
                "配置自动启动",
                "设置服务依赖关系"
            ],
            persistence_locations=[service["location"] for service in deployed_services],
            recommendations=[
                "使用systemd服务获得最佳持久性",
                "伪装成合法系统服务",
                "设置服务重启策略"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def test_startup_script_persistence(self) -> PersistenceTest:
        """测试启动脚本持久化"""
        print("🚀 测试启动脚本持久化场景...")
        
        # 模拟启动脚本位置
        startup_locations = [
            {"path": "/etc/profile.d/system-check.sh", "scope": "all_users", "stealth": 0.6, "survival": 0.85},
            {"path": "/root/.bashrc", "scope": "root", "stealth": 0.7, "survival": 0.80},
            {"path": "/home/user/.profile", "scope": "user", "stealth": 0.8, "survival": 0.75},
            {"path": "/etc/bash.bashrc", "scope": "system", "stealth": 0.5, "survival": 0.90}
        ]
        
        # 模拟脚本注入
        injected_scripts = []
        for location in startup_locations:
            script_info = {
                "path": location["path"],
                "scope": location["scope"],
                "injection_method": "append",
                "payload": self._generate_startup_payload(),
                "stealth": location["stealth"],
                "survival": location["survival"],
                "injected": True
            }
            injected_scripts.append(script_info)
            print(f"  ✅ 注入启动脚本: {location['path']} (范围: {location['scope']})")
        
        # 计算平均指标
        avg_stealth = sum(script["stealth"] for script in injected_scripts) / len(injected_scripts)
        avg_survival = sum(script["survival"] for script in injected_scripts) / len(injected_scripts)
        
        test_result = PersistenceTest(
            test_id="persist_startup_001",
            test_name="启动脚本持久化测试",
            method="startup_script_injection",
            persistence_level="medium",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.5,
            cleanup_difficulty=0.3,
            execution_time=random.uniform(1.0, 4.0),
            artifacts=[
                f"修改 {len(injected_scripts)} 个启动脚本",
                "创建隐藏载荷",
                "设置条件执行"
            ],
            persistence_locations=[script["path"] for script in injected_scripts],
            recommendations=[
                "优先使用用户级配置文件",
                "使用条件判断避免重复执行",
                "伪装成环境变量设置"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def test_user_account_persistence(self) -> PersistenceTest:
        """测试用户账户持久化"""
        print("👤 测试用户账户持久化场景...")
        
        # 模拟用户账户创建
        account_methods = [
            {"type": "hidden_user", "username": ".system", "uid": 1001, "stealth": 0.9, "survival": 0.95},
            {"type": "service_user", "username": "syslog", "uid": 104, "stealth": 0.8, "survival": 0.90},
            {"type": "backup_admin", "username": "backup", "uid": 1002, "stealth": 0.6, "survival": 0.85},
            {"type": "temp_user", "username": "temp", "uid": 1003, "stealth": 0.7, "survival": 0.80}
        ]
        
        # 模拟账户创建过程
        created_accounts = []
        for method in account_methods[:3]:  # 创建前3个
            account_info = {
                "type": method["type"],
                "username": method["username"],
                "uid": method["uid"],
                "home_dir": f"/home/{method['username']}",
                "shell": "/bin/bash",
                "sudo_access": method["type"] in ["backup_admin"],
                "stealth": method["stealth"],
                "survival": method["survival"],
                "created": True
            }
            created_accounts.append(account_info)
            print(f"  ✅ 创建用户账户: {method['username']} (UID: {method['uid']})")
        
        # 计算平均指标
        avg_stealth = sum(account["stealth"] for account in created_accounts) / len(created_accounts)
        avg_survival = sum(account["survival"] for account in created_accounts) / len(created_accounts)
        
        test_result = PersistenceTest(
            test_id="persist_user_001",
            test_name="用户账户持久化测试",
            method="user_account_creation",
            persistence_level="high",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.7,
            cleanup_difficulty=0.5,
            execution_time=random.uniform(2.0, 6.0),
            artifacts=[
                f"创建 {len(created_accounts)} 个用户账户",
                "配置SSH访问",
                "设置用户权限"
            ],
            persistence_locations=[f"/etc/passwd ({account['username']})" for account in created_accounts],
            recommendations=[
                "使用隐藏用户名（以.开头）",
                "模仿系统服务账户",
                "避免给予过高权限"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def test_kernel_module_persistence(self) -> PersistenceTest:
        """测试内核模块持久化"""
        print("🔧 测试内核模块持久化场景...")
        
        # 模拟内核模块持久化
        module_methods = [
            {"type": "rootkit_module", "name": "netfilter_hook", "stealth": 0.95, "survival": 0.98},
            {"type": "driver_module", "name": "usb_monitor", "stealth": 0.85, "survival": 0.95},
            {"type": "network_module", "name": "packet_filter", "stealth": 0.90, "survival": 0.96},
            {"type": "filesystem_module", "name": "file_monitor", "stealth": 0.88, "survival": 0.94}
        ]
        
        # 模拟模块加载
        loaded_modules = []
        for method in module_methods[:2]:  # 加载前2个（内核模块风险较高）
            module_info = {
                "type": method["type"],
                "name": method["name"],
                "path": f"/lib/modules/$(uname -r)/kernel/drivers/{method['name']}.ko",
                "auto_load": True,
                "stealth": method["stealth"],
                "survival": method["survival"],
                "loaded": True
            }
            loaded_modules.append(module_info)
            print(f"  ✅ 加载内核模块: {method['name']} ({method['type']})")
        
        # 计算平均指标
        avg_stealth = sum(module["stealth"] for module in loaded_modules) / len(loaded_modules)
        avg_survival = sum(module["survival"] for module in loaded_modules) / len(loaded_modules)
        
        test_result = PersistenceTest(
            test_id="persist_kernel_001",
            test_name="内核模块持久化测试",
            method="kernel_module_loading",
            persistence_level="critical",
            stealth_rating=avg_stealth,
            survival_rate=avg_survival,
            detection_difficulty=0.95,
            cleanup_difficulty=0.8,
            execution_time=random.uniform(5.0, 12.0),
            artifacts=[
                f"编译 {len(loaded_modules)} 个内核模块",
                "配置模块自动加载",
                "隐藏模块存在"
            ],
            persistence_locations=[module["path"] for module in loaded_modules],
            recommendations=[
                "内核模块持久化风险极高，谨慎使用",
                "需要内核开发经验",
                "仅在高价值目标上使用"
            ]
        )
        
        self.test_results.append(test_result)
        return test_result
    
    def _generate_cron_schedule(self) -> str:
        """生成随机cron调度"""
        schedules = [
            "0 */6 * * *",  # 每6小时
            "*/30 * * * *",  # 每30分钟
            "0 2 * * *",    # 每天凌晨2点
            "0 0 */3 * *"   # 每3天
        ]
        return random.choice(schedules)
    
    def _generate_service_name(self) -> str:
        """生成服务名称"""
        names = [
            "system-monitor",
            "network-check",
            "log-rotator",
            "backup-service",
            "update-checker"
        ]
        return random.choice(names)
    
    def _generate_service_description(self) -> str:
        """生成服务描述"""
        descriptions = [
            "System monitoring and maintenance service",
            "Network connectivity checker",
            "Log rotation and cleanup service",
            "Automated backup service",
            "System update checker"
        ]
        return random.choice(descriptions)
    
    def _generate_startup_payload(self) -> str:
        """生成启动载荷"""
        payloads = [
            "export PATH=$PATH:/tmp/.hidden",
            "[ -f /tmp/.system ] && /tmp/.system &",
            "nohup /usr/local/bin/monitor.sh >/dev/null 2>&1 &",
            "if [ -x /opt/scripts/check.py ]; then /opt/scripts/check.py; fi"
        ]
        return random.choice(payloads)
    
    def run_all_tests(self) -> List[PersistenceTest]:
        """运行所有持久化测试"""
        print("🔒 开始持久化机制场景测试...")
        print("=" * 60)
        
        # 运行各种测试
        self.test_ssh_key_persistence()
        self.test_cron_persistence()
        self.test_service_persistence()
        self.test_startup_script_persistence()
        self.test_user_account_persistence()
        self.test_kernel_module_persistence()
        
        # 计算总体统计
        total_tests = len(self.test_results)
        avg_stealth = sum(test.stealth_rating for test in self.test_results) / total_tests
        avg_survival = sum(test.survival_rate for test in self.test_results) / total_tests
        avg_detection_difficulty = sum(test.detection_difficulty for test in self.test_results) / total_tests
        
        print("\n" + "=" * 60)
        print("📊 持久化测试总结:")
        print(f"  总测试数: {total_tests}")
        print(f"  平均隐蔽性: {avg_stealth:.1%}")
        print(f"  平均存活率: {avg_survival:.1%}")
        print(f"  平均检测难度: {avg_detection_difficulty:.1%}")
        
        # 推荐最佳方法
        best_method = max(self.test_results, key=lambda x: x.stealth_rating * x.survival_rate)
        print(f"  推荐方法: {best_method.test_name}")
        
        return self.test_results
    
    def generate_report(self) -> str:
        """生成持久化测试报告"""
        report_content = f"""# 持久化机制场景测试报告

**目标服务器**: {self.target_host}
**测试时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**测试数量**: {len(self.test_results)}

## 测试结果摘要

"""
        
        for test in self.test_results:
            report_content += f"""### {test.test_name}
- **测试ID**: {test.test_id}
- **方法**: {test.method}
- **持久化级别**: {test.persistence_level}
- **隐蔽性**: {test.stealth_rating:.1%}
- **存活率**: {test.survival_rate:.1%}
- **检测难度**: {test.detection_difficulty:.1%}
- **清理难度**: {test.cleanup_difficulty:.1%}
- **执行时间**: {test.execution_time:.2f}s

**持久化位置**:
{chr(10).join(f'- {location}' for location in test.persistence_locations)}

**发现的问题**:
{chr(10).join(f'- {artifact}' for artifact in test.artifacts)}

**建议**:
{chr(10).join(f'- {rec}' for rec in test.recommendations)}

---

"""
        
        return report_content

def main():
    """主函数"""
    print("🔒 持久化机制场景测试系统")
    print("=" * 40)
    
    # 创建测试器
    tester = PersistenceScenarios()
    
    # 运行所有测试
    results = tester.run_all_tests()
    
    # 生成报告
    report = tester.generate_report()
    
    # 保存报告
    report_file = f"persistence_scenarios_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
    with open(report_file, 'w', encoding='utf-8') as f:
        f.write(report)
    
    print(f"\n📋 报告已保存: {report_file}")

if __name__ == "__main__":
    main()